package com.kaixinff.kaixin001.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kaixinff.kaixin001.util.Filter;
import com.kaixinff.kaixin001.util.KXClient;
import com.kaixinff.kaixin001.util.KXUtil;
import com.kaixinff.kaixin001.util.RegStep;
import com.kaixinff.name.User;
import com.kaixinff.net.HttpClient;

@SuppressWarnings("serial")
public class LogoServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html; charset=" + KXUtil.CHARSET);
		List<User> users = KXUtil.getUsers(new Filter(){
			@Override
			public boolean access(User user) {
				return user.hasStep(RegStep.REG_KX) && !user.hasStep(RegStep.ADD_LOGO);
			}}, resp);
		if (users == null) {
			return;
		}
		
		for (User user : users) {
			KXClient client = KXClient.getInstance(user.getId());
			try {
				logo(client, user);
			} finally {
				KXUtil.saveUsers(users);
			}
		}
	}

	private void logo(HttpClient client, User user) throws IOException  {
		File folder = new File("resources/logo");
		File[] files = folder.listFiles();
		int random = new Random().nextInt(files.length);
		File file = files[random];
		String url = KXUtil.HOST_URL + "/set/upload.php";
		client.doGet(url, null);
		String referer = url;
		url = KXUtil.HOST_URL + "/set/upload_submit.php";
		client.uploadFile(url, referer, file.getAbsolutePath(), null);
		user.addStep(RegStep.ADD_LOGO);
		System.out.println("Succeed in setting logo for " + user.getId());
		/*Pattern p = Pattern.compile("<img id=\"usericon\" src=\"(.+?)\"");
		Matcher m = p.matcher(html);
		String iconimage = null;
		if (m.find()) {
			iconimage = m.group(1);
		} else {
			return;
		}
		conn = client.executeMethod(iconimage, "GET", referer, null);
		byte[] bytes = KXUtil.client.getBytes(conn);*/
		
	}
}
